package probe

import (
	"crypto/tls"
	"log"
	"net/http"
	"net/http/httptrace"
	"time"
)


func HttpProbe(host string,timeout time.Duration) map[string]interface{} {
	// DNS解析时间、建立连接时间、tls握手时间
	var dnsTime,connectTime,tlsTime time.Time
	// 存储结果
	result := make(map[string]interface{})

	client:=&http.Client{Timeout: time.Second*timeout}
	resp, err := client.Get(host)
	if err!=nil{
		log.Println(err)
		return nil
	}

	//获取状态码
	statusCode := resp.StatusCode
	result["statusCode"]=statusCode

	req, _ := http.NewRequest("GET", host, nil)
	// 创建客户端请求跟踪
	trace := &httptrace.ClientTrace{
		// 获取DNS解析耗时
		DNSStart: func(info httptrace.DNSStartInfo) {
			dnsTime = time.Now()
			//fmt.Println(dnsTime)
		},
		DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
			result["dnsTime"]=time.Since(dnsTime)
		},
		// 获取连接耗时及连接的IP
		ConnectStart: func(network, addr string){
			connectTime = time.Now()
		},
		ConnectDone: func(network, addr string, err error){
			result["connectTime"]=time.Since(connectTime)
			result["serverIp"]=addr
			//fmt.Println(addr)
		},
		// 获取https握手时间
		TLSHandshakeStart: func(){
			tlsTime = time.Now()
		},
		TLSHandshakeDone: func(tls.ConnectionState, error){
			result["tlsTime"]=time.Since(tlsTime)
		},
	}

	// 请求追踪
	req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
	_, err = http.DefaultTransport.RoundTrip(req)
	if err != nil {
		log.Fatal(err)
	}
	return result
}

//func main() {
//	probe := httpProbe()
//	for i,v := range probe{
//		fmt.Println(i,v)
//	}
//	//fmt.Println(probe)
//}